import {logout, userChangePass, userInfo, userInfoEdit} from "../../api/models/user";
import {Toast} from "vant";
import {navigateTo} from "../../utils/navigate";
import config from "../../config";
import {removeLoginToken} from "../../utils/db";

export default {
    state: {
        userInfo: {}, // 登录用户信息
    },
    getters: {
        userInfo: (state) => state.userInfo,
    },
    mutations: {
        setUserInfo(state, userInfo) {
            state.userInfo = userInfo;
        },

    },
    actions: {
        // 获取用户信息
        async getUserInfo({dispatch, commit}) {
            let {data} = await userInfo();
            if (data) {
                commit('setUserInfo', data.userInfo)
                return data;
            }
        },

        // 编辑用户信息
        async setUserInfoEdit({dispatch}, payload) {
            let res = await userInfoEdit(payload);
            Toast(res.message);
            if (res.state === 200) {
                dispatch('getUserInfo');
                return true;
            }
            return false;
        },
        // 修改密码
        async setUserChangePass({dispatch}, payload) {
            let res = await userChangePass(payload);
            Toast(res.message);
            if (res.state === 200) {
                return true;
            }
            return false;
        },

        // 退出登录
        async userLogout({dispatch, commit}, payload) {
            const res = await logout({}, payload);
            if (res) {
                removeLoginToken();
                navigateTo(config.loginRouteName)
            }
        }
    }
}
